package pers.w.chaptertalk.funs.db;

import android.content.ContentValues;
import android.content.Context;
import android.content.res.Resources;
import android.database.Cursor;
import android.util.Log;

import androidx.annotation.Nullable;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;

import pers.w.chaptertalk.R;
import pers.w.chaptertalk.funs.BookInfo;
import pers.w.chaptertalk.funs.Fun;

public class Tab_Book extends Tab_Base {

    private static final String NAME = "bookrack";
    private static final String LAST_READ_TIME = "last_read_time";
    private MyDB_Helper dbHelper;
    private Resources resources;
    public static ReentrantLock lock = new ReentrantLock();
    public Tab_Chapter getTab_chapter() {
        return tb_chapter;
    }

    private Tab_Chapter tb_chapter;

    public Tab_BookProgress getTab_bookProgress() {
        return tb_bookProgress;
    }

    private Tab_BookProgress tb_bookProgress;

    static String CREATE_SQL(Resources resources) {
        StringBuilder book_sql = new StringBuilder();
        book_sql.append("CREATE TABLE IF NOT EXISTS " + Tab_Book.NAME + " ( _id integer primary key autoincrement,");

        String[] book_fields = BookInfo.getFieldNames(resources);
        for (int i = 0; i < book_fields.length; i++) {
            book_sql.append(book_fields[i]).append(" varchar,");
        }
        book_sql.append(Tab_Book.LAST_READ_TIME + " integer) ");//最后一个字段单独写
        return book_sql.toString();
    }

    public Tab_Book(@Nullable Context context) {

        assert context != null;
        resources = context.getResources();

        fields = BookInfo.getFieldNames(resources);
        dbHelper = new MyDB_Helper(context);
        this.db = dbHelper.getWritableDatabase();
        tb_chapter = new Tab_Chapter(db);
        tb_bookProgress = new Tab_BookProgress(db);
    }

    public long add(BookInfo bookInfo) {
        return add(bookInfo, null);
    }

    public long add(BookInfo bookInfo, List<Map<String, String>> chapters) {
        long  time=System.currentTimeMillis();

        ContentValues values = new ContentValues();
        for (int i = 0; i < fields.length; i++) {
            values.put(fields[i], bookInfo.getFieldValue(BookInfo.BookInfoFields[i]));
        }
        values.put(LAST_READ_TIME, time);
        long rowid = db.insert(NAME, null, values);
        bookInfo.setID(rowid);
        tb_chapter.add(rowid, chapters);
        tb_bookProgress.add(rowid);
        if (Fun.isDebug()){
            time=System.currentTimeMillis()-time;
            Log.d("sql add", "add: time"+time);
        }
        return rowid;
    }

    public void del(long id) {
        String where = _ID + " = " + id;
        db.delete(NAME, where, null);
        db.delete(Tab_Chapter.NAME, where, null);//同时把章节也删了
        db.delete(Tab_BookProgress.NAME, where, null);//同时把章节也删了
    }

    public void update_lastReadTime(long id) {
        ContentValues values = new ContentValues();
        values.put(LAST_READ_TIME, System.currentTimeMillis());
        db.update(NAME, values, _ID + " = " + id, null);
    }

    public List<BookInfo> get_books() {
        Cursor cursor = db.query(NAME, null, null, null,
                null, null, LAST_READ_TIME + " DESC");
        List<BookInfo> bookInfos = get_bookinfo(cursor);
        cursor.close();
        return bookInfos;
    }

    public List<BookInfo> get_books(long id) {
        Cursor cursor = db.query(NAME, null, _ID + " = " + id,
                null, null, null, LAST_READ_TIME + " DESC");
        List<BookInfo> bookInfos = get_bookinfo(cursor);
        cursor.close();
        return bookInfos;
    }

    //内部使用，通过查询出来的cursor传递，内部读取全部数据
    private List<BookInfo> get_bookinfo(Cursor cursor) {
        cursor.moveToNext();
        List<BookInfo> bookInfos = new ArrayList<>();
        while (!cursor.isAfterLast()) {
            BookInfo bookInfo = new BookInfo();
            bookInfo.setID(cursor.getLong(0));
            for (int i = 0; i < BookInfo.BookInfoFields.length; i++) {
                int col = i + 1;/* cursor.getColumnIndex(fields[i]);//不知道为什么二次调用这里就会出错，错误是空引用，不知道内部什么情况*/
                bookInfo.setFieldValue(BookInfo.BookInfoFields[i], cursor.getString(col));
            }
            cursor.moveToNext();
            bookInfos.add(bookInfo);
        }
        return bookInfos;
    }

    /**
     * 通过书籍的网址判断是否有数据
     *
     * @param url
     * @return 返回的list的 size为0就是没有
     */
    public List<BookInfo> get_books(String url) {
        Cursor cursor = db.query(NAME, null,
                resources.getString(R.string.info_uri) + " = '" + url + "'",
                null, null, null, LAST_READ_TIME + " DESC");
        List<BookInfo> bookInfos = get_bookinfo(cursor);
        cursor.close();
        return bookInfos;
    }

    public void close(){
        if (null != db) {db.close();db =null;}
        if (null != dbHelper) {dbHelper.close();dbHelper=null;}
    }
    @Override
    protected void finalize() throws Throwable {
       close();
        super.finalize();
    }

    public void update(BookInfo bookInfo) {
        long  time=System.currentTimeMillis();

        ContentValues values = new ContentValues();
        for (int i = 0; i < fields.length; i++) {
            values.put(fields[i], bookInfo.getFieldValue(BookInfo.BookInfoFields[i]));
        }
        values.put(LAST_READ_TIME, time);
         db.update(NAME, values, _ID +"="+ bookInfo.getID(), null);

    }
}
